﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HU8.Helpers.Files.Resource;
using System.IO;
using HU8.Helpers.Files.Images;
using System.Drawing;
using System.Drawing.Imaging;

namespace HU8.Helpers.Files
{
    public class ThumbnailHelper
    {
        private static int ThumbWidth = 64;
        private static int ThumbHeight = 64;
        private static int ThumbQuality = 60;
        private static int ThumbCompressionLevel = 60;
        private static int ThumbColorDepth = 256;
        /// <summary>
        /// 生成文件夹中图片的缩略图
        /// </summary>
        /// <param name="path"></param>
        /// <param name="thumbPath"></param>
        public static void GenerateThumbnailsInFolder(string path, string basePath, string thumbPath)
        {
            List<FolderFile> files = FileHelper.GetFileList(path, basePath, "image");
            foreach (FolderFile file in files)
            {
                try
                {
                    string tPath = Path.Combine(thumbPath, file.ThumbnailName);
                    FileInfo fi = new FileInfo(tPath);
                    if (!fi.Exists || fi.LastWriteTime < DateTime.Now.AddHours(-1)) //1个小时timeout
                    {
                        if (".jpg,.jpeg,.bmp,.gif".Contains(fi.Extension))
                        {
                            Image img = ImageHelper.ResizeImage(Image.FromFile(file.Path), ThumbWidth, ThumbHeight, Color.White, Helpers.Images.Models.ResizeStyle.Centre, true);
                            ImageHelper.SaveJpeg(tPath, img, ThumbQuality); //存为JPEG
                            img.Dispose();
                        }
                        else if (".png".Contains(fi.Extension))
                        {
                            Image img = ImageHelper.ResizeImage(Image.FromFile(file.Path), ThumbWidth, ThumbHeight, Color.Transparent, Helpers.Images.Models.ResizeStyle.Centre, true);
                            ImageHelper.SavePng(tPath, img, ThumbCompressionLevel, ThumbColorDepth); //存为PNG
                            img.Dispose();
                        }
                    }
                }
                catch (Exception ex)
                {
                    //无法创建缩略图，极有可能是图片损坏
                }
            }
        }
    }
}
